package com.example.security_demo.service.impl;

import com.example.security_demo.pojo.User;
import com.example.security_demo.pojo.UserDetailsVo;
import com.example.security_demo.service.UserService;
import com.sun.tools.javac.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 *
 * @author zzh
 * @date 2022/5/11
 * @since 1.0
 */
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByMobile(username);
        if (user == null) {

            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 获取相关权限
        List<String> stringAuthorities = List.of("ADMIN", "ROOT", "USER");
        Set<SimpleGrantedAuthority> authorities = stringAuthorities.stream().filter(Objects::nonNull).map(e -> e.length() > 0).map(e -> new SimpleGrantedAuthority("role" + e)).collect(Collectors.toSet());
        return new UserDetailsVo(user, authorities);
    }
}
